﻿using System;
using System.IO;
using System.Net;
using System.Timers;
using VupSlashLauncher.Common;

namespace VupSlashLauncher.Model
{

    public class IDownload : NotifyBase
    {
        private string buttoncontent = "";

        public string ButtonContent
        {
            get { return buttoncontent; }
            set { buttoncontent = value; this.DoNotify(); }
        }


        private int _downloadmax = 100;
        public int DownloadMax
        {
            get { return _downloadmax; }
            set { _downloadmax = value; this.DoNotify(); }
        }

        private int _downloadvalue = 0;
        public int DownloadValue
        {
            get { return _downloadvalue; }
            set { _downloadvalue = value; this.DoNotify(); }
        }

        private string _tasktitle = "";
        public string TaskTitle
        {
            get { return _tasktitle; }
            set { _tasktitle = value; this.DoNotify(); }
        }

        private string _taskname = "";
        public string TaskName
        {
            get { return _taskname; }
            set { _taskname = value; this.DoNotify(); }
        }

        private bool _taskok = true;
        public bool TaskOK
        {
            get { return _taskok; }
            set { _taskok = value; this.DoNotify(); }
        }

        private string _mainviewvisiability = "Collapsed";
        public string MainViewVisiability
        {
            get { return _mainviewvisiability; }
            set { _mainviewvisiability = value; this.DoNotify(); }
        }

        private string _taskviewvisiability = "Collapsed";
        public string TaskViewVisiability
        {
            get { return _taskviewvisiability; }
            set { _taskviewvisiability = value; this.DoNotify(); }
        }

        private string _downloadtext = "";
        public string DownloadText
        {
            get { return _downloadtext; }
            set { _downloadtext = value; this.DoNotify(); }
        }

        private string _downloadspeed = "";
        public string DownloadSpeed
        {
            get { return _downloadspeed; }
            set { _downloadspeed = value; this.DoNotify(); }
        }

        private string _downloadtime = "";
        public string DownloadTime
        {
            get { return _downloadtime; }
            set { _downloadtime = value; this.DoNotify(); }
        }

        private bool _isstart = false;
        public bool IsStart
        {
            get { return _isstart; }
            set { _isstart = value; this.DoNotify(); }
        }

        private bool _ispause = false;
        public bool IsPause
        {
            get { return _ispause; }
            set { _ispause = value; this.DoNotify(); }
        }

        private static bool DoCalcSpeed = false;
        System.Timers.Timer mytimer = new System.Timers.Timer(1000) { AutoReset = true };

        public bool Start(string URL, string fileName)
        {
            IsStart = true;
            IsPause = false;
            mytimer.Elapsed += new ElapsedEventHandler(SpeedChange);
            mytimer.Start();
            DownloadText = "正在访问母星~";
            ButtonContent = "";
            long latestpLength = 0;
            long LStartPos = 0;
            FileStream fs;
            if (File.Exists(fileName))
            {
                fs = File.OpenWrite(fileName);
                LStartPos = fs.Length;
                fs.Seek(LStartPos, SeekOrigin.Current);
            }
            else
            {
                fs = new FileStream(fileName, FileMode.Create);
                LStartPos = 0;
            }
            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(URL);
                request.AddRange(LStartPos);
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                long totalLength = LStartPos + response.ContentLength;
                DownloadMax = (int)totalLength;
                string MaxString = IFunc.GetFileSize(totalLength);
                if (LStartPos * 2 == totalLength)
                {
                    mytimer.Stop();
                    DownloadValue = 0;
                    DownloadText = "下载完成";
                    ButtonContent = "";
                    DownloadSpeed = "";
                    DownloadTime = "";
                    IsStart = false;
                    return true;
                }
                else if (LStartPos < totalLength)
                {
                    Stream ns = response.GetResponseStream();
                    long currentLength = LStartPos;
                    byte[] nbytes = new byte[1024];
                    int osize = 0;
                    osize = ns.Read(nbytes, 0, 1024);
                    while (osize > 0 && currentLength != totalLength)
                    {
                        currentLength = osize + currentLength;
                        fs.Write(nbytes, 0, osize);
                        DownloadValue = (int)currentLength;
                        DownloadText = String.Format("{0} / {1}", IFunc.GetFileSize(currentLength), MaxString);
                        if (DoCalcSpeed && DownloadSpeed != null && DownloadTime != null)
                        {
                            DownloadSpeed = string.Format("{0}/s", IFunc.GetFileSize((currentLength - latestpLength)));
                            DownloadTime = ((totalLength - currentLength) / (currentLength - latestpLength)).ToString() + "秒";
                            latestpLength = currentLength;
                            DoCalcSpeed = false;
                        }
                        osize = ns.Read(nbytes, 0, nbytes.Length);
                        if (IsPause)
                        {
                            DownloadText = "下载暂停";
                            ButtonContent = "";
                            DownloadSpeed = "";
                            DownloadTime = "";
                            while (IsPause)
                            {
                                if (!IsStart)
                                {
                                    mytimer.Stop();
                                    fs.Close();
                                    ns.Close();
                                    DownloadValue = 0;
                                    DownloadText = "任务取消";
                                    ButtonContent = "";
                                    DownloadSpeed = "";
                                    DownloadTime = "";
                                    return false;
                                }
                            }
                            ButtonContent = "";
                        }
                    }
                    request.Abort();
                    response.Close();
                    fs.Close();
                    ns.Close();
                }
            }
            catch
            {
                fs.Close();
                GlobalValues.HaveNet = false;
                DownloadText = "网络异常，下载暂停";
                ButtonContent = "";
                DownloadSpeed = "";
                DownloadTime = "";
                IsStart = false;
                return false;
            }
            mytimer.Stop();
            DownloadValue = 0;
            DownloadText = "下载完成";
            ButtonContent = "";
            DownloadSpeed = "";
            DownloadTime = "";
            IsStart = false;
            return true;
        }
        public static void SpeedChange(object sender, ElapsedEventArgs e)
        {
            DoCalcSpeed = true;
        }
    }
}
